//
// Created by yyancy on 2019/10/26.
//

#include "state.h"
#include <stdio.h>

void init(state *s) {
    for (int i = 0; i < 3; ++i)
        for (int j = 0; j < 3; ++j)
            s->board[i][j] = -1;
    s->turn = 0;
}


void display(const state *s) {
    printf("+---+---+---+\n");
    for (int i = 0; i < 3; ++i) {
        printf("|");
        for (int j = 0; j < 3; ++j) {
            switch (s->board[i][j]) {
                case -1:
                    printf(" %d ", i * LINE + j + 1);
                    break;
                case 0:
                    printf(" O ");
                    break;
                case 1:
                    printf(" X ");
                    break;
            }
            printf("|");
        }
        printf("\n+---+---+---+\n");
    }


}

#define RANGE(i) ((i)>=0 && (i)< LINE)

int move(state *s, int i, int j) {
    printf("i=%d,j=%d\n", i, j);
    if (!RANGE (i) || !RANGE (j))
        return 0;
    if (s->board[i][j] != -1)
        return 0;
    s->board[i][j] = s->turn++ % 2;
    return 1;
}

#undef RANGE

void human(state *s) {
    char c;
    do {
        printf("请输入编号(1-9) %c:\n", "OX"[s->turn % 2]);
        c = getchar();
        while (getchar() != '\n');
        printf("\n");
    } while (c < '1' || c > '9' || !move(s, (c - '1') / LINE, (c - '1') % LINE));
}

#define CHECK(i1, j1, i2, j2, i3, j3) \
    if (s->board[i1][j1]!=-1 &&s->board[i1][j1] == s->board[i2][j2] && s->board[i1][j1] == s->board[i3][j3]) \
        return s->board[i1][j1] == 0? 1:-1;

int evaluate(const state *s) {


    for (int i = 0; i < LINE; ++i) {
        CHECK(i, 0, i, 1, i, 2)
        CHECK(0, i, 1, i, 2, i)
    }
    CHECK(0, 0, 1, 1, 2, 2)
    CHECK(0, 2, 1, 1, 2, 0)
    return 0;
}

#undef CHECK